/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 */
define(['N/search', 'N/record', "N/http"], function (search, record, http) {

    function getInputData() {
        return search.create({
            type: 'customrecord_fba_inbound_shipment',
            columns: ['custrecord_inbound_po'],
            filters: [['custrecord_inbound_po', 'isnotempty', ''],
                'and', ['custrecord_inbound_so', 'is', '@NONE@']]
        }).run().getRange(0, 50);
    }

    function map(context) {
        var recId = JSON.parse(context.value).id;
        var result = JSON.parse(context.value).values;
        var poId = result['custrecord_inbound_po'][0].value;
        log.debug('poId', poId);
        try {
            var soId;
            search.create({
                type: 'salesorder',
                columns: ['status', 'intercostatus'],
                filters: [['intercotransaction', 'is', poId],
                    'and', ['intercostatus', 'is', 2],// 2 Paired
                    'and', ['status', 'is', 'pendingFulfillment']]
            }).run().each(function (result) {
                soId = result.id;
            });
            if (soId) {//自动发货
                var ifId;
                search.create({
                    type: 'itemfulfillment',
                    columns: [],
                    filters: [['createdfrom', 'is', soId]]
                }).run().each(function (result) {
                    ifId = result.id;
                });
                if (ifId) {
                    //存在销售发货单,不进行操作
                } else {
                    var itemfulfillment = record.transform({
                        fromType: 'salesorder',
                        fromId: soId,
                        toType: 'itemfulfillment',
                        isDynamic: false
                    });
                    itemfulfillment.setValue('shipstatus', 'C');
                    ifId = itemfulfillment.save();
                }
                record.submitFields({
                    type: 'customrecord_fba_inbound_shipment',
                    id: recId,
                    values: {
                        custrecord_inbound_so: soId
                    }
                });
            }
        } catch (e) {
            log.debug('e', e);
        }

    }

    function reduce(context) {
    }

    function summarize(summary) {
    }


    return {
        getInputData: getInputData,
        map: map,
        reduce: reduce,
        summarize: summarize
    };
});